#!/bin/sh

# generate host keys if not present
ssh-keygen -A

# set root login mode by password or keypair
if [ "${KEY_LOGIN}" = 'true' ];then
    echo "Init Key ..."
    if [ ! -f '/root/.ssh/id_rsa' ]; then
        ssh-keygen -q -N "" -t rsa -f /root/.ssh/id_rsa
    fi
    if [ `grep -rn $(cat /root/.ssh/id_rsa.pub) /root/.ssh/authorized_keys  | wc -l` -eq 0 ];then
        cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys
    fi
    cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
    sed -i "s/#PermitRootLogin.*/PermitRootLogin without-password/" /etc/ssh/sshd_config
    sed -i "s/#PasswordAuthentication.*/PasswordAuthentication no/" /etc/ssh/sshd_config
    PASS="$(head /dev/urandom | tr -cd a-zA-Z0-9 | head -c 10)"
    echo "root:${ROOT_PASS:-$PASS}" | chpasswd
    echo "==> Enabled root-login by keypair and disabled password-login"
else
    echo "Init Password ..."
    cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
    sed -i "s/#PermitRootLogin.*/PermitRootLogin yes/g" /etc/ssh/sshd_config
    echo "root:${ROOT_PASS:-admin}" | chpasswd
    echo "==> Enabled root-login by password"
fi

# do not detach (-D), log to stderr (-e), passthrough other arguments
# exec /usr/sbin/sshd -D -e "$@"
exec "$@"
